﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Xml.Serialization;
using System.Xml;

namespace Sync3DCartDatabase
{
    /// <summary>
    /// This class will 
    /// </summary>
    public class ConfigHandler : IConfigurationSectionHandler
    {
        /// <summary>
        /// Convert configuration to ServiceConfig
        /// </summary>
        /// <returns></returns>
        public object Create(object parent, object configContext, System.Xml.XmlNode section)
        {
            ServiceConfig config = new ServiceConfig();
            try
            {
                config.SyncInterval = Convert.ToInt32(section.SelectSingleNode("SyncInterval").InnerText);
                config.WorkingFolderPath = section.SelectSingleNode("WorkingFolder").InnerText;
                config.SourceFolderPath = section.SelectSingleNode("SourceFolderPath").InnerText;

                XmlSerializer mappingSerializer = new XmlSerializer(typeof(MappedColumnsDetails));
                using (XmlReader reader = new XmlNodeReader(section.SelectSingleNode("ColumnsMappingDetails")))
                {
                    config.MappedColumnsDetail = (MappedColumnsDetails)mappingSerializer.Deserialize(reader);
                }

                XmlSerializer serializer = new XmlSerializer(typeof(CSessionOptionCDO));
                using (XmlReader reader = new XmlNodeReader(section.SelectSingleNode("FTPSessionOptionInfo")))
                {
                    config.FTPConnectionInfo = (CSessionOptionCDO)serializer.Deserialize(reader);
                }

                XmlSerializer cartSerializer = new XmlSerializer(typeof(CartConnectionInfo));
                using (XmlReader reader = new XmlNodeReader(section.SelectSingleNode("CartConnectionInfo")))
                {
                    config.cartConnectionInfo = (CartConnectionInfo)cartSerializer.Deserialize(reader);
                }

                LogMessage(MessageWriter.ISEnumLogLevel.INFO, "Configuartion successfully read");
            }
            catch (Exception ex)
            {
                LogMessage(MessageWriter.ISEnumLogLevel.ERROR, ex.ToString());
                config = null;
            }
            return config;
        }

        #region Logging
        private void LogMessage(MessageWriter.ISEnumLogLevel logLevel, string message)
        {
            MessageWriter.EventMessage(message, logLevel, this.GetType().FullName);
        }
        #endregion
    }
}
